/**
 * 송수신내용 표시
 * 클라이언트 관리
 * 송신할 클라이언트 선택
 */

package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class MultiChatServer extends JFrame implements Runnable{

	ServerSocket server = null;
	Socket client = null;
	boolean tFlag =false;//스레드의 반복여부
	StringBuilder data = new StringBuilder();
	MultiChatServerThread mcst =null;//클라이언트당 하나씩 발생
	int port = 4444;
	//클라이언트를 관리
	HashMap<String, MultiChatServerThread> clients = new HashMap<String, MultiChatServerThread>();
	DefaultListModel<String> model = new DefaultListModel<String>();
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JTextField message;
	private JButton btnSend;
	private JScrollPane scrollPane;
	JList list;
	private JScrollPane scrollPane_1;
	private JTextPane result;
	private JComboBox comboBox;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JPanel panel_2;
	private JButton btnServerStart;
	private JButton btnServerStop;
	private JLabel lblNewLabel_2;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatServer frame = new MultiChatServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MultiChatServer() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 739, 547);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.WEST);
		contentPane.add(getScrollPane_1(), BorderLayout.CENTER);
		try {
		InetAddress ia = InetAddress.getLocalHost();
		String ip = ia.getHostAddress();
		setTitle("IP: "+ip+" port: "+port);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	//서버시작 -> 클라이언트 접속 대기(run()매서드)-> mcst생성 후 map에 저장
	
	@Override
	public void run() {
		try {
			server = new ServerSocket(port);// ServerSocket생성

			tFlag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		while (tFlag) {
			try {
				client = server.accept();// 클라이언트 접속대기/서버가끝나기전까지 반복적으로, 클라이언트접속!
				
//				if (!client.getInetAddress().getHostAddress().equals("127.0.0.1")) {
//					mcst = new MultiChatServerThread(this, client);
//					mcst.start();
//				}
				
				mcst = new MultiChatServerThread(this, client);
				mcst.start();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	
	//오버로딩(다형화) dataSet
	public void dataSet(SocketData sd){//JTextPane에 문자열을 추가하기 위해서
		String icon = "";
		if(sd.getIndex() >0){
			icon = "<img src = 'file:\\H:\\JAVA\\ht\\1403\\ori"+sd.getIndex()+".gif' width='100' heigth='100'><br>";
			data.append(icon);
		}
		data.append(sd.getUser() + " : " + sd.getMessage());
		data.append("<br/>");
		result.setText(data.toString());
	}
	
	//오버로딩(다형화) dataSet
	public void dataSet(String d){
		data.append(d);
		data.append("<br/>");
		result.setText(data.toString());
	}
	
	//자신의 스레드를 생성하고 시작한다.
	public void serverStart(){
		Thread t = new Thread(this);
		t.start();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String str = sd.format(new Date());
		dataSet("<div style='border:1px solid #ff0000; background-color:#ffdddd'> "+
		 " 서버가 시작되었습니다.<br>"+
		  "서버 시작시간 "+str+"<br></div>");
		btnSend.setEnabled(true);
		 
//		dataSet("<hr>"+"<font color ='blue' size='5'><b>서버가 시작되었습니다.</b></font><br>서버시작시간 : "+str+"<br><hr>");
	}
	
	public void serverStop(){
//		
//		try {
//			tFlag = false;
//		
//		//server.accept()의 blocking mode 해제
//		Socket s = new Socket("127.0.0.1",4444);
//		
//		//접속된 유저들에게 서버가 중지되었습을 전달하기 위해
//		SocketData d = new SocketData("serverDown", "server", "서버가 종료S.", null);
//		
//		if(!clients.isEmpty()) mcst.sendMsg(d);
//		
//		ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
//		oos.writeObject(d);
//		
//		btnSend.setEnabled(false);
//		btnServerStop.setEnabled(false);
//		btnServerStart.setEnabled(true);
//		
//		clients.clear();
//		list.setListData(new Vector());
//	
//			if(server!=null) server.close();
//		} catch (Exception e) {
//			
//		}
//		
	}
	
	public void sendMsg(){
		try {
			SocketData soc = new SocketData("message", "환영합니다 주인님", message.getText(), null);
			mcst.sendMsg(soc);
			dataSet(soc);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_2(), BorderLayout.EAST);
			panel.add(getLblNewLabel_2(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getMessage(), BorderLayout.CENTER);
			panel_1.add(getBtnSend(), BorderLayout.EAST);
			panel_1.add(getComboBox(), BorderLayout.WEST);
		}
		return panel_1;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
						sendMsg();
					}else if(arg0.getKeyCode() == KeyEvent.VK_ESCAPE){
						message.setText("");
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("전송");
			btnSend.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					sendMsg();
				}
			});
		}
		return btnSend;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getList());
			scrollPane.setColumnHeaderView(getLblNewLabel());
		}
		return scrollPane;
	}
	private JList getList() {
		if (list == null) {
			list = new JList(model);
		}
		return list;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setViewportView(getResult());
			scrollPane_1.setColumnHeaderView(getLblNewLabel_1());
		}
		return scrollPane_1;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
		}
		return comboBox;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("접속자");
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("채    팅");
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_1;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.add(getBtnServerStart());
			panel_2.add(getBtnServerStop());
		}
		return panel_2;
	}
	private JButton getBtnServerStart() {
		if (btnServerStart == null) {
			btnServerStart = new JButton("서버시작");
			btnServerStart.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverStart();
				}
			});
		}
		return btnServerStart;
	}
	private JButton getBtnServerStop() {
		if (btnServerStop == null) {
			btnServerStop = new JButton("서버종료");
			btnServerStop.setEnabled(false);
			btnServerStop.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverStop();
				}
			});
		}
		return btnServerStop;
	}
	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("환영합니다 어서오세요~");
			lblNewLabel_2.setFont(new Font("양재다운명조M", Font.BOLD, 14));
			lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_2;
	}
}
